package jdk8.stream;

import java.util.*;
import java.util.stream.Collectors;

public class MapDemo {
    public static void main(String[] args) {
        int[] arr = {1, 2, 2, 5, 5, 5, 3, 3, 4, 4, 4, 4};
        Map<Integer, Integer> result = getDuplicates(arr);
        for (Map.Entry<Integer, Integer> entry : result.entrySet()) {
            System.out.println(entry.getKey() + " occurs " + entry.getValue() + " times");
        }
    }

        /**
     * 获取数组中的重复元素
     *
     * @param arr 数组
     * @return 重复元素的集合
     */
    public static Map<Integer, Integer> getDuplicates(int[] arr) {
        Map<Integer, Integer> counts = new HashMap<>();
        for (int num : arr) {
            counts.put(num, counts.getOrDefault(num, 0) + 1);
        }
        Map<Integer, Integer> duplicates = new HashMap<>();
        for (Map.Entry<Integer, Integer> entry : counts.entrySet()) {
            if (entry.getValue() > 1) {
                duplicates.put(entry.getKey(), entry.getValue());
            }
        }
        return duplicates;
    }

}
